const http = require('http')
const path = require('path')
const fs = require('fs')

const url = 'http://static.micheliafigo.xyz/books/1581347142049.jpeg'
const targetFile = path.join(__dirname, '../file/image.jpeg')
const SINGLE = 1024 * 10
// const SINGLE = 80000

class Chunk {
  constructor() {
    this.deleteFile()
    this.req = this.httpHEAD()
    // this.req.write()
    this.req.end()
  }

  deleteFile() {
    // delete
    let files = fs.existsSync(targetFile)
    files &&
      fs.unlinkSync(targetFile, function(err) {
        if (err) throw err
      })
  }

  httpGet(index, isEnd, size) {
    let start = index * SINGLE
    let end = isEnd ? size - 1 : (index + 1) * SINGLE - 1
    http.get(
      url,
      {
        headers: {
          Range: `bytes=${start}-${end}`,
          'If-Range': 'FF70503A7175D736D973ECE83554EE84'
        }
      },
      response => {
        let _buf
        // onData
        response.on('data', chunk => {
          chunk = Buffer.from(chunk) //监听数据响应，拼接数据片段
          if (!_buf) {
            _buf = chunk
          } else {
            let _length = _buf.length + chunk.length // 可以省略
            _buf = Buffer.concat([_buf, chunk], _length)
          }
        })
        // end
        response.on('end', () => {
          console.log(_buf)
          console.log(`start:${start},end:${end}`)
          // write
          fs.open(targetFile, 'as+', function(err, fd) {
            fs.writeSync(fd, _buf, 0, _buf.length, start, err => {
              if (err) throw err
            })
          })
        })

        // response.pipe(fs.createWriteStream(targetFile, { start, end }))
      }
    )
  }

  httpHEAD() {
    return http.request(url, { method: 'HEAD' }, response => {
      let { 'content-length': contentLength } = response.headers

      this.rangeGet(contentLength)
      // console.log(response.headers)
      response.on('end', () => {})
    })
  }

  rangeGet(contentLength) {
    const size = Number(contentLength)
    const length = parseInt(size / SINGLE)
    // chunk-download
    for (let i = 0; i < length; i++) {
      this.httpGet(i, i === length - 1, size)
    }
  }
}

let buf = new Chunk()
